package com.dhcy.mqtt.iden;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dhcy.mqtt.config.ProjectConfig;
import com.dhcy.mqtt.dao.RedisDao;
import com.dhcy.mqtt.exception.GlobalException;
import com.dhcy.mqtt.util.AppResultData;
import com.dhcy.mqtt.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author zll
 * @version 1.0
 * @date 2021/3/18 10:57
 */
@Slf4j
@Component
public class IdenUtil {



    @Autowired
    private ProjectConfig projectConfig;
    @Autowired
    private RedisDao redisDao;


    public static void main(String[] args) {
       // log.info(getModel("86.122.2","笔记本"));
    }

    public  boolean modelExist(String url,String username,String password,String prefix,String name){
        String token=getLoginToken(url,username,password);
        String reqUrl=url+"/snms/api/template/v1";
        log.info(reqUrl);
        Map<String,Object> map=new HashMap<>();
        map.put("prefix",prefix);
        map.put("version",name);
        String result= HttpRequest.get(reqUrl).form(map)
                .header("Content-type","application/x-www-form-urlencoded;charset=utf-8")
                .header("Authorization", "Bearer " + token)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Integer status = jsonObject.getInt("status");
        return status != -2;
    }

    public   Map<String,Object> initModelItem(String nameEn,String nameCh,String required,int min,int max){
        Map<String,Object> map=new HashMap<>();
        map.put("name",nameCh);
        map.put("idType",nameEn);
        map.put("required",required);
        Map<String,String> valueMap=new HashMap<>();
        valueMap.put("type","string");
        valueMap.put("minLength",min+"");
        valueMap.put("maxLength",max+"");
        map.put("metadata",valueMap);
        return  map;
    }

    public   Map<String,Object> initModelItem(String nameEn,String nameCh){
        Map<String,Object> map=new HashMap<>();
        map.put("name",nameCh);
        map.put("idType",nameEn);
        map.put("required","false");
        Map<String,String> valueMap=new HashMap<>();
        valueMap.put("type","string");
        valueMap.put("minLength","0");
        valueMap.put("maxLength","1000");
        map.put("metadata",valueMap);
        return  map;
    }



    public void regModel(String url,String username,String password,String prefix,String modelName,String desc,List<Map<String,Object>> dataList,int times){
        Map<String,Object> hadleMap=new HashMap<>();
        hadleMap.put("prefix",prefix);
        hadleMap.put("version",modelName);
        if(desc!=null){
            hadleMap.put("description",desc);
        }
        hadleMap.put("items",dataList);
        String regUrl = url+"/snms/api/template/v1";
        String token=getLoginToken(url,username,password);
        String result = HttpRequest.post(regUrl)
                .header("Authorization", "Bearer " + token)
                .body(JSONUtil.toJsonStr(hadleMap))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Integer status=jsonObject.getInt("status");
        if(status!=1){
            log.error(result);
            if(times>3){
                throw new GlobalException(AppResultData.errorMessage("模板注册失败"));
            }
            times++;
            regModel(url,username,password,prefix,modelName,desc,dataList,times);
        }
    }
    public void regModel(String url,String username,String password,String prefix,String name,List<Map<String,Object>> dataList,int times){
       regModel(url,username,password,prefix,name,"1.0.0",dataList,times);
    }

    public Map<String, Object> initItem(String index, String name, String value){
        Map<String,Object> map=new HashMap<>();
        map.put("type",name);
        map.put("index",index);
        Map<String,String> valueMap=new HashMap<>();
        valueMap.put("format","string");
        valueMap.put("value",value);
        map.put("data",valueMap);
        return  map;
    }

    public   Map<String, Object>  initHandle(String handle, String template, List<Map<String,Object>> dataList){
        Map<String,Object> hadleMap=new HashMap<>();
        hadleMap.put("handle",handle);
        hadleMap.put("templateVersion",template);
        hadleMap.put("value",dataList);
        return hadleMap;
    }

    public  void  batchHandleReg(String url,String username,String password,List<Map<String,Object>> handleList,int times){
        String regUrl = url+"/identityv2/data/batchCreate";
        String token=getLoginToken(url,username,password);
        String result = HttpRequest.post(regUrl)
                .header("Authorization", "Bearer " + token)
                .body(JSONUtil.toJsonStr(handleList))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Integer status=jsonObject.getInt("status");
        if(status!=1){
            log.error(result);
            if(times>3){
                throw new GlobalException(AppResultData.errorMessage("标识注册失败"));
            }
            times++;
            batchHandleReg(url,username,password,handleList,times);
        }
    }

    public void regIden(String url,String username,String password,String handle, String template, List<Map<String,Object>> dataList){
        Map<String,Object> hadleMap=new HashMap<>();
        hadleMap.put("handle",handle);
        hadleMap.put("templateVersion",template);
        hadleMap.put("value",dataList);
        String regUrl = url+"/identityv2/data";
        String token=getLoginToken(url,username,password);
        String result = HttpRequest.post(regUrl)
                .header("Authorization", "Bearer " + token)
                .body(JSONUtil.toJsonStr(hadleMap))
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(jsonObject.getInt("status")!=1){
            log.error("注册失败:"+JSONUtil.toJsonStr(jsonObject));
            throw new GlobalException(AppResultData.errorMessage(jsonObject.getStr("message")));
        }

    }





    private String getLoginToken(String url,String username, String password) {
        String token=redisDao.getValue(RedisUtil.SNMSTOKEN);
        if(token!=null){
            return token;
        }
        String loginUrl =  url+"/identity/token";
        Map<String, String> loginMap = new HashMap<>();
        loginMap.put("username", username);
        loginMap.put("password", password);
        String result = HttpUtil.post(loginUrl, JSONUtil.toJsonStr(loginMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        token=jsonObject.getJSONObject("data").getStr("token");
        redisDao.putSecondValue(RedisUtil.SNMSTOKEN,token,60*60*10);
        return  token;
    }




}
